package com.bdth.mixapi.controller;

import com.bdth.mixapi.api.vo.CommonMessage;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.NestedServletException;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by Administrator on 2019/4/10.
 */
@Controller
public class ErrorResultController implements ErrorController {
    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping(value="/error")
    @ResponseBody
    public CommonMessage handleError(HttpServletRequest request){
        //获取statusCode:401,404,500
        Integer code = (Integer) request.getAttribute("javax.servlet.error.status_code");
        Enumeration<String> message = request.getAttributeNames();
        String msg = (String) request.getAttribute("javax.servlet.error.message");
        String name = (String) request.getAttribute("javax.servlet.error.servlet_name");
        NestedServletException exception = (NestedServletException) request.getAttribute("javax.servlet.error.exception");
        if(exception != null) {
            return CommonMessage.message(String.valueOf(code), exception.toString() );
        }else{
            return CommonMessage.message(String.valueOf(code), msg);
        }
    }
}
